package com.blog.service.impl;

import com.blog.dao.ArticlesDao;
import com.blog.dao.CommentDao;
import com.blog.dao.UserDao;
import com.blog.dao.impl.ArticlesDaoImpl;
import com.blog.dao.impl.CommentDaoImpl;
import com.blog.dao.impl.UserDaoImpl;
import com.blog.pojo.Articles;
import com.blog.pojo.Comment;
import com.blog.pojo.User;
import com.blog.service.CommentService;
import com.blog.websocket.NotificationWebSocket;

import java.util.List;

public class CommentServiceImpl implements CommentService {
    private CommentDao commentDao=new CommentDaoImpl();

    private UserDao userDao = new UserDaoImpl();

    private ArticlesDao articlesDao = new ArticlesDaoImpl();

    @Override
    public boolean addComment(Comment comment) {
        int add = commentDao.addComment(comment);
        if(add>0){
            User commentUser = userDao.findUserById(comment.getUserId());
            Articles articles = articlesDao.findById(comment.getArticleId());
            sendCommentNotify(commentUser.getUsername(), articles.getTitle(), articles.getUserId().toString());
            return true;
        }
        return false;
    }

    public void sendCommentNotify(String commenter, String title, String articleAuthorId) {
        NotificationWebSocket.NotificationMessage message =
            new NotificationWebSocket.NotificationMessage(
                "comment",
                "新评论提醒",
                commenter + " 评论了您的文章"+","+title,
                title,
                commenter
            );

        // 发送通知给文章作者
        System.out.println(String.format("发送通知给文章作者, 评论人:%s, 文章标题:%s,作者ID:%s", commenter, title, articleAuthorId));
        NotificationWebSocket.sendNotification(articleAuthorId, message);
    }

    @Override
    public boolean deleteComment(int id) {
        int delete = commentDao.deleteComment(id);
        if(delete>0){
            return true;
        }
        return false;
    }

    @Override
    public List<Comment> findAll() {
        return commentDao.findAll();
    }

    @Override
    public List<Comment> findByAuthor(String author) {
        return commentDao.findByAuthor(author);
    }

    @Override
    public List<Comment> findByTitle(String title) {
        return commentDao.findByTitle(title);
    }

    @Override
    public boolean updateComment(Comment comments) {
        int update = commentDao.updateComment(comments);
        if(update==1){
            return true;
        }
        return false;
    }

    @Override
    public Comment findById(int id) {
        return commentDao.findById(id);
    }

    @Override
    public List<Comment> findByUserIdAndArticleId(int userId, int articleId) {
        return commentDao.findByUserIdAndArticleId(userId,articleId);
    }

    @Override
    public List<Comment> findByArticleId(int articleId) {
        return commentDao.findByArticleId(articleId);
    }
}
